package com.ruoyi.app.controller;

import com.alipay.api.domain.MemberInfo;
import com.ruoyi.app.interceptor.JWTUtil;
import com.ruoyi.cms.domain.CrmMember;
import com.ruoyi.cms.service.ICrmMemberService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.md5.MD5;
import com.ruoyi.common.sms.SMSResult;
import com.ruoyi.common.sms.biz.SMSClient;
import com.ruoyi.common.utils.uuid.GeneratorUtil;
import com.ruoyi.customer.domain.CrmCustomer;
import com.ruoyi.customer.service.ICrmCustomerService;
import com.ruoyi.employee.domain.CrmEmployee;
import com.ruoyi.employee.service.ICrmEmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;
/**
 * @author hct
 * @date 2019/08/15
 */
@RequestMapping("/app/public")
@RestController
public class AppLoginController extends BaseController {

    @Autowired
    private ICrmEmployeeService employeeService;

    @Autowired
    private ICrmCustomerService customerService;
    @Autowired
    private ICrmMemberService memberService;

    @Autowired
    private SMSClient smsClient;

    @Autowired
    private RedisCache redisCache;
    @PostMapping("/login")
    @ResponseBody
    public AjaxResult login(HttpServletRequest request, String phoneNumber,String password)
    {
        if(StringUtils.isEmpty(phoneNumber)){
            return AjaxResult.error("未填写手机号");
        }
        if(StringUtils.isEmpty(password)){
            return AjaxResult.error("未填写，登陆密码");
        }
        CrmMember crmMember=new CrmMember();
        crmMember.setMobile(phoneNumber);
        String passwordmd5=MD5.md5Hex(password);
        crmMember.setPassword(passwordmd5);
        List<CrmMember> list= memberService.selectCrmMemberList(crmMember);
        if(list!=null && list.size()>0){
            CrmMember crmMember1=list.get(0);
            if(crmMember1.getIdentity().intValue()>0) {
                CrmEmployee crmEmployee = employeeService.selectCrmEmployeeById(crmMember1.getEmployeeId());
                crmMember1.setCrmEmployee(crmEmployee);
                CrmCustomer crmCustomer = customerService.selectCrmCustomerById(crmMember1.getCustomerId());
                crmMember1.setCrmCustomer(crmCustomer);
            }
            String token=JWTUtil.generateJWT(crmMember1.getId()+"_"+phoneNumber);
            redisCache.setCacheObject(Constants.MEMBER_TOKEN + token,crmMember1);
            // 生成令牌
            AjaxResult ajaxResult= AjaxResult.success();
            ajaxResult.put("data",token);
            return ajaxResult;
        }else {

            //redisCache.setCacheMapValue(Constants.MEMBER_TOKEN + accessToken,);
            return AjaxResult.error("账号密码错误");
        }
    }

    /**
     * 手机号+验证码登陆
     * @param request
     * @param phoneNumber
     * @param code
     * @return
     */
    @PostMapping("/loginByMobileAndCode")
    @ResponseBody
    public AjaxResult loginByMobileAndCode(HttpServletRequest request, String phoneNumber,String code)
    {
        if(StringUtils.isEmpty(phoneNumber)){
            return AjaxResult.error("未填写手机号");
        }
        if(StringUtils.isEmpty(code)){
            return AjaxResult.error("未填写验证码");
        }
        String verifyCode=(String)request.getSession().getAttribute("verifyCode");
        if(verifyCode==null || !code.equals(verifyCode)){
            return AjaxResult.error("验证码错误");
        }
        // 生成令牌
        CrmMember crmMember=new CrmMember();
        crmMember.setMobile(phoneNumber);
        List<CrmMember> list= memberService.selectCrmMemberList(crmMember);
        if(list!=null && list.size()>0){
            CrmMember crmEmployee1=list.get(0);
            String token=JWTUtil.generateJWT(crmEmployee1.getId()+"_"+phoneNumber);
            redisCache.setCacheObject(Constants.MEMBER_TOKEN + token,crmEmployee1);
            // 生成令牌
            AjaxResult ajaxResult= AjaxResult.success();
            ajaxResult.put("token",token);
            return ajaxResult;
        }else {

            //redisCache.setCacheMapValue(Constants.MEMBER_TOKEN + accessToken,);
            return AjaxResult.error("账号密码错误");
        }

    }

   /**
     * 找回密码   获取验证码
     * @return
     */
    @GetMapping("/checkPhoneCode")
    @ResponseBody
    public AjaxResult checkPhoneCode(HttpServletRequest request, String phoneNumber){
        if (!employeeService.checkPhoneUnique(phoneNumber))
        {
            return AjaxResult.error("手机号不存在");
        }
        //获取手机验证码
        String verifyCode = GeneratorUtil.genSixVerifyCode();
        SMSResult res = smsClient.sendRegisterVerify(phoneNumber, verifyCode);
        if (res.isSucc()) {
            //五分钟 验证码过期
            request.getSession().setAttribute("verifyCode", verifyCode);
        } else {
            return AjaxResult.error(res.getMsg());
        }
        return AjaxResult.success("success");
    }

    /**
     * 找回密码
     * @param phoneNumber
     * @param code
     * @param password
     * @param repassword
     * @return
     */
    @PostMapping("/findPassword")
    @ResponseBody
    public AjaxResult findPassword(String phoneNumber,String code,String password,String repassword)
    {
        if(StringUtils.isEmpty(phoneNumber)){
            return AjaxResult.error("未填写手机号");
        }
        //TODO
        if(StringUtils.isEmpty(code)){
            return AjaxResult.error("未填写验证码");
        }
        if(StringUtils.isEmpty(password)){
            return AjaxResult.error("未填写，登陆密码");
        }
        if(!repassword.equals(password)){
            return AjaxResult.error("两次输入密码不一致");
        }

        // 生成令牌
        CrmMember memberInfo = memberService.getByMobile(phoneNumber);
        //ajax.put(Constants.TOKEN, token);
        if(memberInfo!=null && memberInfo.getId()>0){
            String passwordmd5=MD5.md5Hex(password);
            memberInfo.setPassword(passwordmd5);
            memberService.updateCrmMember(memberInfo);
            return AjaxResult.success("修改成功");
        }else{
            return AjaxResult.error("修改失败");
        }

    }



    public static void inputStreamToFile (InputStream ins, File file){
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }





    
    public static File getNetUrlHttp(String netUrl) {
        //对本地文件命名
    	UUID uuid = UUID.randomUUID();
    	String fileName=uuid.toString();
        File file = null;
        URL urlfile;
        InputStream inStream = null;
        OutputStream os = null;
        try {
            file = File.createTempFile("net_url", URLEncoder.encode(fileName));
            //下载
            urlfile = new URL(netUrl);
            inStream = urlfile.openStream();
            os = new FileOutputStream(file);
 
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
                if (null != inStream) {
                    inStream.close();
                }
 
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
 
        return file;
    }
}